package com.lyw.GeoLocationClient.ui;

import android.app.*;
import android.content.*;
import android.net.Uri;
import android.os.*;
import android.provider.Settings;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.baidu.mapapi.SDKInitializer;
import com.easemob.chatui.activity.MainActivity;
import com.lyw.GeoLocationClient.App;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.utils.LoginCallback;
import com.lyw.GeoLocationClient.service.LBSClient;

import static com.lyw.GeoLocationClient.utils.LogUtils.LOGD;

public class LoginActivity extends Activity implements OnClickListener {

	private Button login, register;
	private EditText name, pwd;
	private String rname, rpwd;
	public String nid = null;
	public ProgressDialog loginProDialog;

    private LBSClient mClient;
    private boolean flag;
    private SDKReceiver mReceiver;

    private ProgressDialog progressDialog;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_login);
//        SDKInitializer.initialize(getApplicationContext());

        mClient = LBSClient.getInstance();
        if (mClient == null) {
            LOG("start bind service");
            bindService();
        }

        if (getActionBar() != null) {
            getActionBar().show();
        }

		login = (Button) findViewById(R.id.login_btn);
		register = (Button) findViewById(R.id.login_register);
		name = (EditText) findViewById(R.id.name);
		pwd = (EditText) findViewById(R.id.pwd);

		login.setOnClickListener(this);
		register.setOnClickListener(this);

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);

//		Intent intent = getIntent();
//        if (intent.getStringExtra("phone") != null) {
//            Log.d("Login phone", intent.getStringExtra("phone"));
//            rname = intent.getStringExtra("phone");
//            rpwd = intent.getStringExtra("pwd");
//            name.setText(rname);
//            pwd.setText(rpwd);
//        }

        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);

        CheckPermission();
    }


    private void CheckPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                Uri selfPackageUri = Uri.parse("package:"
                        + getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                        selfPackageUri);
                startActivity(intent);
            }
        }
    }


    @Override
    protected void onResume() {
        if (App.DEBUG) {
            if (App.isAdmin()) {
                name.setText("ee");
                pwd.setText("ee");
            } else {
                name.setText("ee");
                pwd.setText("ee");
            }
        }
        if (mClient != null) {
            if (mClient.isLogin()) {
//                if (mClient.isAdmin()) {
//                    startAdminActivity();
//                } else {
//                    makeToast(getResources().getString(R.string.location_started));
//                    startScanActivity();
//                }
                startLauncherActivity();
                finish();
            }
        }

        super.onResume();
    }

    private void showProgress(String msg) {
        progressDialog.setMessage(msg);
        progressDialog.show();
    }


    private void hideProgress() {
        if (progressDialog != null
                && progressDialog.isShowing())
        progressDialog.cancel();
    }

    private void startLauncherActivity() {
        startActivity(new Intent(this, LauncherActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    }

    private void startAdminActivity() {
        LOG("startAdminActivity");

        startActivity(new Intent(this, MapActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

    }

    private void startMainChatActivity() {
        LOG("startMainChatActivity");

        startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

    }

    private void startScanActivity() {
        LOG("start scan activity");
        startActivity(new Intent(this, RadarActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

    }

    private LoginCallback uiCallback = new LoginCallback() {
        @Override
        public void onRegister(boolean success) {
            enableButtons();
            hideProgress();
            if (success) {
                makeToast(getResources().getString(R.string.register_success));
                if (mClient.isAdmin()) {
                    startAdminActivity();
                } else {
                    startScanActivity();
                }
            } else {
                makeToast(getResources().getString(R.string.register_failed));
            }
        }

        @Override
        public void onLogin(final boolean success) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    enableButtons();
                    hideProgress();
                    if (success) {
                        makeToast(getResources().getString(R.string.login_success));
                    } else {
                        makeToast(getResources().getString(R.string.login_failed));
                    }

                    if (mClient != null) {
                        if (success) {
                            startLauncherActivity();
                            finish();
                        }
                    }
                }
            });

        }

    };

    private void bindService() {
        Intent intent = new Intent(this, LBSClient.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private void unBind(){
        if(flag){
            unbindService(conn);
            flag = false;
            mClient.setLoginCallback(null);
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            LOG("connected service");
            LBSClient.MyBinder binder = (LBSClient.MyBinder) service;
            mClient = binder.getService();
            flag = true;
            mClient.setLoginCallback(uiCallback);
        }
    };

	@Override
	public void onClick(View v) {
        if (!flag) {
            mClient.setLoginCallback(uiCallback);
        }
		switch (v.getId()) {
            case R.id.login_btn:
                disableButtons();
                doLogin(getEditViewText(name), getEditViewText(pwd));
                showProgress(getResources().getString(R.string.logining));
                break;
            case R.id.login_register:
                disableButtons();
                doRegister(getEditViewText(name), getEditViewText(pwd));
                showProgress(getResources().getString(R.string.registering));
                break;
            default:
                break;
        }

	}

    private void enableButtons() {
        login.setEnabled(true);
        register.setEnabled(true);

    }

    private void disableButtons() {
        login.setEnabled(false);
        register.setEnabled(false);
    }

    private void doLogin(String name, String passwd) {
        if (mClient != null) {
            mClient.login(name, passwd);
        }
    }

    private String getEditViewText(EditText v) {
        return v.getText() == null ? "":v.getText().toString();
    }

    private void doRegister(String name, String passwd) {
        if (mClient != null) {
            mClient.register(name, passwd);
        }
    }

    public void makeToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public class SDKReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            LOG("action " + s);
            if (s != null) {
                if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                    makeToast("key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
                } else if (s
                        .equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                    makeToast("网络出错");
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消监听 SDK 广播
        unBind();
        unregisterReceiver(mReceiver);
        hideProgress();
    }




    public void LOG(String msg) {
        LOGD(this.getClass(), msg);
    }

}